// pages/adminlogin/adminlogin.ts

Page({

    /**
     * 页面的初始数据
     */
    data: {
        account: '',
        password: ''
    },
    // 获取账号
    bindAccount(e) {
        this.setData({
            account: e.detail.value
        })
    },
    // 获取密码
    bindPassword(e) {
        this.setData({
            password: e.detail.value
        })
    },
    // 登陆功能
    login() {
        let account = this.data.account
        let password = this.data.password
        if (account === "") {
            wx.showToast({
                title: 'Please fill your account',
                icon: 'none'
            })
            return
        }
        if (password === "") {
            wx.showToast({
                title: 'Please fill your password',
                icon: 'none'
            })
            return
        }
        let reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,}$/;
        if (!reg.test(account)) {
            wx.showToast({
                title: 'The account cannot have special characters',
                icon: 'none'
            })
            return false;
        }
        let regPwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,}$/;
        if (!regPwd.test(password)) {
            wx.showToast({
                title: 'Password must contain uppercase letters, lowercase letters and numbers, and be at least 8 digits long',
                icon: 'none'
            })
            return false;
        }
        wx.cloud.callFunction({
            name: 'loginAdmin',
            data: {
                account: account,
                password: password
            },
        }).then(res => {
            console.log('Administrator login successful', res.result);
            wx.showToast({
                title: 'Administrator login successful',
                icon: 'success'
            })
            wx.navigateTo({
                url: '../homePage/homePage',
            })
            // 保护用户登陆状态，将用户信息存储到Storage
            // @ts-ignore
            wx.setStorageSync('user', res.result.data)
        }).catch(err => {
            console.log('Administrator login failed', err);
            wx.showToast({
                title: 'Login failed, please check if the account password is correct or if you are an administrator',
                icon: 'none'
            })
        })
    }
})